<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
        <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
        <link rel="stylesheet" type="text/css" href="./css/aui.2.0.css" />
        <style type="text/css">
            .header {
                padding: 0rem 0.5 rem 0.5 rem 0.5 rem;
            }
        </style>
    </head>
    <body>
        <header class="aui-bar aui-bar-nav" id="aui-header">
            <a class="aui-btn aui-pull-left" tapmode onclick="backToFirstPage()"> <span id="backIcon" style="display:none" class="aui-iconfont aui-icon-left"></span> </a>
            <div id='appHeader' class="aui-title">
                贷款之家
            </div>
        </header>
        <footer class="aui-bar aui-bar-tab" id="footer" style="border-top: 0.5px solid #efefef; background-color: #f8f8ff">
            <div class="aui-bar-tab-item aui-active" tapmode>
                <i class="aui-iconfont aui-icon-home"></i>
                <div class="aui-bar-tab-label">
                    首页
                </div>
            </div>
            <div class="aui-bar-tab-item" tapmode>
                <i class="aui-iconfont aui-icon-cart"></i>
                <div class="aui-bar-tab-label">
                    贷款
                </div>
            </div>
            <div class="aui-bar-tab-item" tapmode>
                <i class="aui-iconfont aui-icon-comment"></i>
                <div class="aui-bar-tab-label">
                    论坛
                </div>
            </div>
            <div class="aui-bar-tab-item" tapmode>
                <i class="aui-iconfont aui-icon-my"></i>
                <div class="aui-bar-tab-label">
                    我的
                </div>
            </div>
        </footer>
    </body>
    <script type="text/javascript" src="./script/aui-tab.js" ></script>
    <script type="text/javascript" src="./script/api.js"></script>
    <script type="text/javascript" src="./script/APICloud-rest-SHA1.js" ></script>
    <script type="text/javascript" src="./script/aui-toast.js" ></script>
    <script type="text/javascript" src="./script/aui-dialog.js" ></script>
    <script type="text/javascript" src="./script/jquery-3.2.0.min.js" ></script>
    <script type="text/javascript">
        var header_h;
        var footer_h;
        var frame_name;
        var header_names = ["贷款之家", "贷款", "论坛", "我的"];
        var loan_type_index = 0;
        var old_index = 1;
        var toast = new auiToast();
        var dialog = new auiDialog();
        var alertId;
        var client = new Resource("A6928874653494", "4B6C428C-24C2-F9E7-3175-F983922E8C8F");
        function displayForumLoading() {
            header_h = $api.offset($api.dom('header')).h;
            footer_h = $api.offset($api.byId('footer')).h;
            api.closeFrame({
                name : 'forum_loading',
            })
            api.openFrame({
                name : 'forum_loading',
                url : './html/main_frames/forum_loading.html',
                bounces : true,
                rect : {
                    x : 0,
                    y : header_h,
                    w : 'auto',
                    h : api.winHeight - header_h - footer_h,
                }
            })
        }

        function testForumLinkAndRun(callback, errHandle) {
            $.ajax({
                "url" : "http://139.224.165.165/loanMarket/api/forum",
                "type" : "GET",
                "cache" : false,
            }).done(function(data, status, header) {
                //alert(JSON.stringify(status));
                callback();
            }).fail(function(header, status, errorThrown) {
                if (errHandle != null) {
                    errHandle();
                }
                //alert(JSON.stringify(status));
            })
        }

        function loadOldForumFrame() {
            api.bringFrameToFront({
                from : 'main_frm_3'
            });
        }

        function loadForumFrame() {
            api.openFrame({
                name : 'main_frm_3',
                url : 'http://139.224.165.165/loanMarket/',
                bounces : true,
                rect : {
                    x : 0,
                    y : header_h,
                    w : 'auto',
                    h : api.winHeight - header_h - footer_h,
                },
                animation : {
                    type : "fade", //动画类型（详见动画类型常量）
                    subType : "from_left", //动画子类型（详见动画子类型常量）
                    duration : 200 //动画过渡时间，默认300毫秒
                }
            });
            api.sendFrameToBack({
                from : 'main_frm_3'
            });
        }

        function loginForumDirectly() {
            var jsforum = '';
            jsforum += "app.session.login(\'" + $api.getStorage('username') + "\', \'" + $api.getStorage('password') + "\', null)";
            jsforum += ".then(() => window.location.reload(),null);";
            //alert(jsforum);
            api.execScript({
                frameName : 'main_frm_3',
                script : jsforum,
            });
        }

        function autoLoginForum() {
            api.openFrame({
                name : 'main_frm_3',
                url : 'http://139.224.165.165/loanMarket/',
                bounces : true,
                rect : {
                    x : 0,
                    y : header_h,
                    w : 'auto',
                    h : api.winHeight - header_h - footer_h,
                },
                animation : {
                    type : "fade", //动画类型（详见动画类型常量）
                    subType : "from_left", //动画子类型（详见动画子类型常量）
                    duration : 200 //动画过渡时间，默认300毫秒
                }
            });
            var forumUser = $api.getStorage('forumUser');
            var currentUser = $api.getStorage('username');
            var jsforum = '';
            if ( typeof (currentUser) == 'undefined' || currentUser != forumUser) {
                jsforum += "window.onload=function(){";
                jsforum += "if(typeof (app.session.user) == \'undefined\'){";
                if ( typeof (currentUser) != 'undefined') {
                    jsforum += "app.session.login(\'" + $api.getStorage('username') + "\', \'" + $api.getStorage('password') + "\', null)";
                    jsforum += ".then(() => window.location.reload(),null);";
                    $api.setStorage('forumUser', currentUser);
                    displayForumLoading();
                    setTimeout(function() {
                        api.closeFrame({
                            name : 'forum_loading'
                        });
                    }, 3000);
                }
                jsforum += "}";
                jsforum += "else{";
                jsforum += "if(app.session.user.email() == \'" + currentUser + "\'){";
                jsforum += ";"
                jsforum += "}else{";
                jsforum += "app.session.logout.bind(app.session);";
                if ( typeof (currentUser) != 'undefined') {
                    jsforum += "app.session.login(\'" + $api.getStorage('username') + "\', \'" + $api.getStorage('password') + "\', null)";
                    jsforum += ".then(() => window.location.reload(),null);";
                    displayForumLoading();
                    setTimeout(function() {
                        api.closeFrame({
                            name : 'forum_loading'
                        });
                    }, 3000);
                }
                jsforum += "}";
                jsforum += "}";
                jsforum += "}";
                //jsforum += "alert(\'Bad\')";
                //setTimeout(function() {
                api.execScript({
                    frameName : 'main_frm_3',
                    script : jsforum,
                })
                //}, 5000);
            }
        }

        function openMainFrame(index) {
            old_index = index;
            var backIcon = document.getElementById("backIcon");
            if (index == 1) {
                backIcon.style.display = 'none';
            } else {
                backIcon.style.display = 'block';
            }
            var frm_url = './html/main_frames/main_frm_' + index + '.html';
            api.bringFrameToFront({
                from : 'background'
            });
            api.sendFrameToBack({
                from : frame_name
            });
            frame_name = 'main_frm_' + index;
            var options = {
                header_h : header_h,
                index : loan_type_index
            };
            if (index == 3) {
                testForumLinkAndRun(autoLoginForum, loadOldForumFrame);
                //var jsfun = "app.session.login(\'15800520964\', \'11111111\', null);window.location.reload();";
            } else {
                api.openFrame({
                    name : 'main_frm_' + index,
                    url : frm_url,
                    bounces : true,
                    rect : {
                        x : 0,
                        y : header_h,
                        w : 'auto',
                        h : api.winHeight - header_h - footer_h,
                    },
                    pageParam : options,
                    animation : {
                        type : "fade", //动画类型（详见动画类型常量）
                        subType : "from_left", //动画子类型（详见动画子类型常量）
                        duration : 200 //动画过渡时间，默认300毫秒
                    }
                });
            }
            var appHeader = document.querySelector('#appHeader');
            appHeader.textContent = header_names[index - 1];
        }

        function backToFirstPage() {
            openMainFrame(1);
            var tabItems = document.getElementById("footer").children;
            for (var i = 0; i < tabItems.length; i++) {
                tabItems[i].classList.remove("aui-active");
            }
            tabItems[0].classList.add("aui-active");
        }

        function userLogin() {
            var delay = 0;
            if (api.systemType != 'ios') {
                delay = 300;
            }
            api.openWin({
                name : 'user_login_win',
                url : './html/main_frames/user_login_win.html',
                bounces : false,
                delay : delay,
                slidBackEnabled : true,
                vScrollBarEnabled : false,
                animation : {
                    type : "movein", //动画类型（详见动画类型常量）
                    subType : "from_left", //动画子类型（详见动画子类型常量）
                    duration : delay //动画过渡时间，默认300毫秒
                }
            });
        }

        function openMyFrame() {
            api.sendEvent({
                name : 'ev_openMyFrame',
                extra : {
                    option : 0,
                }
            });
        }

        apiready = function() {
            api.removeLaunchView({
                animation : {
                    type : 'fade',
                    duration : 0
                }
            });
            $api.fixStatusBar($api.dom('header'));
            api.setStatusBarStyle({
                style : 'dark',
                color : '#03a9f4'
            });
            api.parseTapmode();
            $api.setStorage('forumUser', '');
            frame_name = 'main_frm_1';
            header_h = $api.offset($api.dom('header')).h;
            footer_h = $api.offset($api.byId('footer')).h;
            //testForumLinkAndRun(loadForumFrame, null);
            api.openFrame({
                name : 'background',
                url : './html/main_frames/background.html',
                bounces : false,
                rect : {
                    x : 0,
                    y : header_h,
                    w : 'auto',
                    h : api.winHeight - header_h - footer_h,
                }
            })
            var options = {
                header_h : header_h,
                index : 1
            };
            api.openFrame({
                name : frame_name,
                url : './html/main_frames/main_frm_1.html',
                bounces : true,
                rect : {
                    x : 0,
                    y : header_h,
                    w : 'auto',
                    h : api.winHeight - header_h - footer_h,
                },
                pageParam : options,
                animation : {
                    type : "fade", //动画类型（详见动画类型常量）
                    subType : "from_left", //动画子类型（详见动画子类型常量）
                    duration : 200 //动画过渡时间，默认300毫秒
                }
            })
            api.addEventListener({
                name : 'ev_openLoanListFrame'
            }, function(ret2, err) {
                loan_type_index = ret2.value.option;
                openMainFrame(2);
                var tabItems = document.getElementById("footer").children;
                for (var i = 0; i < tabItems.length; i++) {
                    tabItems[i].classList.remove("aui-active");
                }
                tabItems[1].classList.add("aui-active");
            });
            api.addEventListener({
                name : 'ev_openFirstFrame'
            }, function(ret2, err) {
                openMainFrame(1);
                var tabItems = document.getElementById("footer").children;
                for (var i = 0; i < tabItems.length; i++) {
                    tabItems[i].classList.remove("aui-active");
                }
                tabItems[0].classList.add("aui-active");
            });
            api.addEventListener({
                name : 'ev_openMyFrame'
            }, function(ret2, err) {
                openMainFrame(4);
                var tabItems = document.getElementById("footer").children;
                for (var i = 0; i < tabItems.length; i++) {
                    tabItems[i].classList.remove("aui-active");
                }
                tabItems[3].classList.add("aui-active");
            });
            api.addEventListener({
                name : 'ev_openLoanManagementFrame'
            }, function(ret2, err) {
                var db = api.require('db');
                db.selectSql({
                    name : 'loanMarketDB',
                    sql : 'SELECT * FROM UserInfo'
                }, function(ret, err) {
                    if (ret.status) {
                        //alert("select tbl: " + JSON.stringify(ret));
                        if (ret.data.length) {
                            //alert(JSON.stringify(ret));
                            openMainFrame(3);
                            var tabItems = document.getElementById("footer").children;
                            for (var i = 0; i < tabItems.length; i++) {
                                tabItems[i].classList.remove("aui-active");
                            }
                            tabItems[2].classList.add("aui-active");
                        } else {
                            api.closeFrame({
                                name : 'main_frm_3'
                            });
                            userLogin();
                        }
                    } else {
                        alert(JSON.stringify(ret));
                    }
                });
            });
            api.addEventListener({
                name : 'ev_openMyFrame'
            }, function(ret2, err) {
                openMainFrame(4);
                var tabItems = document.getElementById("footer").children;
                for (var i = 0; i < tabItems.length; i++) {
                    tabItems[i].classList.remove("aui-active");
                }
                tabItems[3].classList.add("aui-active");
            });
            api.addEventListener({
                name : 'ev_forum_login'
            }, function(ret2, err) {
                loginForumDirectly();
            });
            var db = api.require('db');
            db.openDatabase({
                name : 'loanMarketDB'
            }, function(ret, err) {
                if (ret.status) {
                    //alert("creat db: " + JSON.stringify(ret));
                    db.selectSql({
                        name : 'loanMarketDB',
                        sql : 'SELECT * FROM UserInfo'
                    }, function(ret, err) {
                        if (ret.status) {
                            //alert("select tbl: " + JSON.stringify(ret));
                            if (ret.data.length) {
                                $api.setStorage('userID', ret.data[0].Id_P);
                                $api.setStorage('username', ret.data[0].Phone);
                            }
                            /*
                             db.executeSql({
                             name : 'loanMarketDB',
                             sql : 'DROP TABLE UserInfo'
                             }, function(ret, err) {
                             if (ret.status) {
                             alert("DROP tbl: " + JSON.stringify(ret));
                             } else {
                             alert("DROP tbl: " + JSON.stringify(err));
                             }
                             });*/
                        } else {
                            //alert("select tbl: " + JSON.stringify(err));
                            db.executeSql({
                                name : 'loanMarketDB',
                                sql : 'CREATE TABLE UserInfo(Id_P varchar(255), Phone varchar(255), Password varchar(255), Login int)'
                            }, function(ret, err) {
                                if (ret.status) {
                                    //alert("creat tbl: " + JSON.stringify(ret));
                                } else {
                                    alert("creat tbl: " + JSON.stringify(err));
                                }
                            });
                        }
                    });
                } else {
                    alert("creat db: " + JSON.stringify(err));
                }
            });
            alertId = setInterval(checkAlert, 1000);
        };
        function checkAlert() {
            var modelUser = client.Factory("user");
            if ( typeof ($api.getStorage('userID')) != "undefined") {
                modelUser.query({
                    filter : {
                        "limit" : 1,
                        "where" : {
                            "id" : $api.getStorage('userID')
                        }
                    }
                }, function(ret, err) {
                    if (err) {
                        //处理错误 err
                        alert(JSON.stringify(err));
                    } else {
                        //处理数据 ret
                        //alert(JSON.stringify(ret));
                        if (ret.length) {
                            if (ret[0].enableAlert) {
                                checkLoanDate();
                            }
                        }
                    }
                });
            }
        }

        function calcPayProgress(e) {
            var myDate = new Date();
            var year = parseInt(myDate.getFullYear());
            var month = parseInt(myDate.getMonth()) + 1;
            var day = parseInt(myDate.getDate());
            var oldYear = parseInt(e.validYear);
            var oldMonth = parseInt(e.validMonth);
            var oldDay = parseInt(e.validDay);
            if (e.payTypeIndex == 1) {
                var curDayCount = year * 365 + (month - 1) * 30 + day;
                var payDayCount = oldYear * 365 + (oldMonth - 1) * 30 + oldDay + e.loanPeriod;
                if (curDayCount > payDayCount) {
                    return 100.00;
                } else {
                    return 0;
                }
            } else {
                var payMonth = 0;
                yearDiff = year - oldYear;
                if (yearDiff > 0) {
                    payMonth = (yearDiff - 1) * 12 + (12 - oldMonth + 1) + (month - 1);
                } else if (yearDiff == 0) {
                    //alert("Date: " + year + " " + month + " " + day);
                    monthDiff = month - oldMonth;
                    if (monthDiff > 0) {
                        payMonth = monthDiff;
                    } else if (monthDiff < 0) {
                        return 0;
                    }
                } else if (yearDiff < 0) {
                    return 0;
                }
                if (day > oldDay) {
                    payMonth = payMonth + 1;
                }
                var PayRate = payMonth * 100.00 / e.loanPeriod;
                if (PayRate > 100.00) {
                    PayRate = 100.00;
                }
                return PayRate;
            }
            //alert("Date: " + oldYear + " " + oldMonth + " " + oldDay);
        }

        function checkRecentPay(loanListItem) {
            var alertRequired = 0;
            var myDate = new Date();
            var year = parseInt(myDate.getFullYear());
            var month = parseInt(myDate.getMonth()) + 1;
            var day = parseInt(myDate.getDate());
            var oldYear = parseInt(loanListItem.validYear);
            var oldMonth = parseInt(loanListItem.validMonth);
            var oldDay = parseInt(loanListItem.validDay);
            //alert("day: " + day + " oldDay: " + oldDay);
            var dayDiff = oldDay - day;
            if (loanListItem.payTypeIndex == 1) {
                var curDayCount = year * 365 + (month - 1) * 30 + day;
                var payDayCount = oldYear * 365 + (oldMonth - 1) * 30 + oldDay;
                var countDiff = payDayCount - curDayCount;
                if (countDiff > 0 && countDiff < 5) {
                    alertRequired = 1;
                    //alert(count);
                }
            } else {
                if (dayDiff > 0 && dayDiff < 5) {
                    alertRequired = 1;
                    //alert(count);
                }
            }
            return alertRequired;
        }

        function checkLoanDate() {
            var modelUserLoanRecord = client.Factory("userLoanRecord");
            modelUserLoanRecord.query({
                filter : {
                    "order" : "createdAt DESC",
                    "where" : {
                        "userId" : $api.getStorage('userID')
                    }
                }
            }, function(ret, err) {
                if (err) {
                    //处理错误 err
                    alert(JSON.stringify(err));
                } else {
                    //处理数据 ret
                    loanList = ret;
                    //alert(JSON.stringify(ret));
                    var count = 0;
                    for (var i = 0; i < loanList.length; i++) {
                        var myDate = new Date();
                        var year = parseInt(myDate.getFullYear());
                        var month = parseInt(myDate.getMonth()) + 1;
                        monthCount = year * 12 + month;
                        if (monthCount == loanList[i].banAlertMonth) {
                            continue;
                        }
                        var alertRequired = 0;
                        var calcRate = calcPayProgress(loanList[i]);
                        if (calcRate < 100.00) {
                            alertRequired = checkRecentPay(loanList[i]);
                            count = count + alertRequired;
                        }
                    };
                    if (count) {
                        clearInterval(alertId);
                        alertId = setInterval(checkAlert, 300000);
                        setTimeout(function() {
                            //alert('还款！');
                            displayAlert();
                        }, 3000)
                    } else {
                        clearInterval(alertId);
                        alertId = setInterval(checkAlert, 5000);
                    }
                }
            });
        }

        function displayAlert() {
            header_h = $api.offset($api.dom('header')).h;
            footer_h = $api.offset($api.byId('footer')).h;
            api.closeFrame({
                name : 'alert_loan',
            })
            api.openFrame({
                name : 'alert_loan',
                url : './html/main_frames/alert_loan.html',
                bounces : true,
                rect : {
                    x : 0,
                    y : header_h,
                    w : 'auto',
                    h : api.winHeight - header_h - footer_h,
                }
            })
        }

        var tab = new auiTab({
            element : document.getElementById("footer")
        }, function(ret) {
            console.log(ret);
            if (ret) {
                if (ret.index == 3) {
                    /*
                     var db = api.require('db');
                     db.selectSql({
                     name : 'loanMarketDB',
                     sql : 'SELECT * FROM UserInfo'
                     }, function(ret2, err) {
                     if (ret2.status) {
                     //alert("select tbl: " + JSON.stringify(ret));
                     if (ret2.data.length) {
                     openMainFrame(ret.index);
                     } else {
                     api.closeFrame({
                     name : 'main_frm_3'
                     });
                     openMainFrame(old_index);
                     var tabItems = document.getElementById("footer").children;
                     for (var i = 0; i < tabItems.length; i++) {
                     tabItems[i].classList.remove("aui-active");
                     }
                     tabItems[old_index - 1].classList.add("aui-active");
                     userLogin();
                     return;
                     }
                     } else {
                     alert(JSON.stringify(ret2));
                     }
                     });*/
                    openMainFrame(ret.index);
                    toast.loading({
                        title : "加载中",
                        duration : 1000
                    }, function(ret) {
                        console.log(ret);
                        setTimeout(function() {
                            toast.hide();
                        }, 3000)
                    });
                } else {
                    openMainFrame(ret.index);
                }
            }
        });
        function closeWin() {
            api.closeWin({
            });
        }

        //Zxfy-2016
    </script>
</html>